const WebSocket = require("ws");
const http = require("http");

// 创建HTTP服务器
const server = http.createServer();

// 创建WebSocket服务器
const wss = new WebSocket.Server({
  server,
  path: "/ws",
  verifyClient: (info) => {
    console.log("握手验证:", {
      url: info.req.url,
      method: info.req.method,
      upgrade: info.req.headers.upgrade,
      connection: info.req.headers.connection,
    });
    return true;
  },
});

wss.on("connection", (ws, req) => {
  console.log("===== 新连接 =====");
  console.log("连接时间:", new Date().toISOString());
  console.log("连接状态:", ws.readyState);
  console.log("来源URL:", req.url);

  const clientId = Math.random().toString(36).substr(2, 9);
  console.log("分配客户端ID:", clientId);

  // 立即发送欢迎消息
  setImmediate(() => {
    if (ws.readyState === WebSocket.OPEN) {
      try {
        ws.send(
          JSON.stringify({
            type: "welcome",
            clientId: clientId,
            message: "连接成功",
            timestamp: new Date().toISOString(),
          })
        );
        console.log("欢迎消息已发送:", clientId);
      } catch (error) {
        console.error("发送欢迎消息失败:", error.message);
      }
    } else {
      console.error("连接状态异常:", ws.readyState);
    }
  });

  ws.on("message", (data) => {
    console.log("收到消息:", data.toString());
    try {
      const message = JSON.parse(data);
      // 简单回复
      ws.send(
        JSON.stringify({
          type: "echo",
          original: message,
          timestamp: new Date().toISOString(),
        })
      );
    } catch (error) {
      console.error("处理消息失败:", error.message);
    }
  });

  ws.on("close", (code, reason) => {
    console.log("===== 连接关闭 =====");
    console.log("客户端ID:", clientId);
    console.log("关闭代码:", code);
    console.log("关闭原因:", reason.toString());
    console.log("关闭时间:", new Date().toISOString());
  });

  ws.on("error", (error) => {
    console.error("WebSocket错误:", error.message);
  });
});

wss.on("error", (error) => {
  console.error("WebSocket服务器错误:", error);
});

// 启动服务器
const PORT = 3001; // 使用不同的端口避免冲突
server.listen(PORT, () => {
  console.log(`🧪 最简WebSocket测试服务器启动: ws://localhost:${PORT}/ws`);
});

// 优雅关闭
process.on("SIGINT", () => {
  console.log("\n正在关闭服务器...");
  server.close(() => {
    console.log("服务器已关闭");
    process.exit(0);
  });
});
